<?php
declare(strict_types=1);

namespace app\common\job;

use app\common\enums\QuestionTypeEnum;
use app\common\model\banxi\learn\LearnReadingArticleAnswer;
use app\common\model\banxi\learn\LearnReadingArticleExtend;
use app\common\service\DouBaoAiArticleQuestionService;
use think\facade\Log;
use think\queue\Job;

/*
 * ai文章生成句子结构
 * */
class AiArticleSentenceStructureRunner
{
    public function fire(Job $job, array $data): void
    {
        logSave([
            'file' => __FILE__,
            'message' => 'AiArticleSentenceStructureRunner Exec',
            'data' => $data,
            'start_time' => date('Y-m-d H:i:s')
        ], 'AiArticleSentenceStructureRunner');
        $articleContent = $data['articleContent'];
        $readingArticleExtendId = $data['readingArticleExtendId'];
        try {
            // 调用AI服务生成短句
            $DouBaoAiArticleQuestionService = new DouBaoAiArticleQuestionService();
            $result = $DouBaoAiArticleQuestionService->getArticleSentenceStructureByContent($articleContent);
            // 保存题目信息
            if ($result) {
                // 保存短语信息
                logSave($result, 'ai文章生成句子结构');
                LearnReadingArticleExtend::update([
                    'articleSentenceStructure' => json_encode($result, JSON_UNESCAPED_UNICODE)
                ], ['id' => $readingArticleExtendId]);

                // 任务执行成功，删除任务
//                $job->delete();

            } else {
                // 任务执行失败，处理失败情况
//                $this->handleFailure($job, $data);
            }
            $job->delete();
        } catch (\Exception $e) {
            // 捕获异常并处理失败情况
            $this->handleFailure($job, $data);
            logSave([
                'file' => __FILE__,
                'message' => "AiArticleSentenceStructureRunner Exception",
                'data' => $data,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 'AiArticleSentenceStructureRunner');
        } catch (\Throwable $t) {
            // 捕获致命错误
            $this->handleFailure($job, $data);
            logSave([
                'file' => __FILE__,
                'message' => "AiArticleSentenceStructureRunner Throwable",
                'data' => $data,
                'error' => $t->getMessage(),
                'trace' => $t->getTraceAsString()
            ], 'AiArticleSentenceStructureRunner');
        }
    }

    /**
     * 处理任务失败情况
     */
    private function handleFailure(Job $job, array $data): void
    {
        $attempts = $job->attempts();

        // 如果重试次数超过3次，则删除任务并记录失败
        if ($attempts > 3) {
            $job->delete();
            logSave([
                'file' => __FILE__,
                'message' => "队列任务失败超过3次，已删除",
                'data' => $data,
                'attempts' => $attempts,
                'end_time' => date('Y-m-d H:i:s')
            ], 'AiArticleSentenceStructureRunner');
        } else {
            logSave([
                'file' => __FILE__,
                'message' => "队列任务失败，将自动重试",
                'data' => $data,
                'attempts' => $attempts,
            ], 'AiArticleSentenceStructureRunner');
            // 任务会自动重新加入队列
        }
    }

    /**
     * 默认任务处理
     */
    private function processDefault(array $data): bool
    {
        // 实现默认处理逻辑
        return true;
    }

    /**
     * 任务失败回调
     */
    public function failed(array $data): void
    {
        // 记录失败任务日志
        Log::error('队列任务最终失败', $data);
    }
}
